import { env } from '@/shared/constants/env';
import { ResponseType } from '@/shared/interfaces';
import { storage } from '@/shared/lib/storage';

export default async function request<TResponse, TRequest = any>(
  url: string,
  method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH',
  body?: TRequest,
  headers?: HeadersInit,
): Promise<TResponse & ResponseType> {
  const baseURL = env.apiUrl;
  const accessToken = storage.getAccessToken();

  const ans = await fetch(baseURL + url, {
    method,
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${accessToken}`,
      ...headers,
    },
    body: JSON.stringify(body),
    credentials: 'include',
  });

  const getAnsData = async (response: Response) => {
    try {
      return await response.json();
    } catch (err: any) {
      return {};
    }
  };

  const { status } = ans;

  const data = await getAnsData(ans);

  if (status !== 200 && status !== 201 && status !== 204) {
    return {
      ...data,
      statusCode: 1,
      message: data.message,
    };
  }
  return data;
}
